<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <link rel="stylesheet" href="styles/style.css">
        <link rel="stylesheet" href="styles/theme/atom-one-dark.css">
        <title>例子15-ES6/7常用语法介绍</title>
    </head>
    <body>
        <pre>
            <code>
                // 例子15

                // 应用1：过滤HTML字符串，防止用户输入恶意内容
                function SaferHTML(templateData) {
                    let s = templateData[0];
                    for (let i = 1; i < arguments.length; i++) {
                        let arg = String(arguments[i]);

                        // Escape special characters in the substitution.
                        s += arg.replace(/&/g, "& amp;")
                                .replace(/&lt;/g, "& lt;")
                                .replace(/&gt;/g, "& gt;");

                        // Don't escape special characters in the template.
                        s += templateData[i];
                    }
                    return s;
                }

                let sender = '&lt;script&gt;alert("abc")&lt;/script&gt;'; // 恶意代码
                let message = SaferHTML`&lt;p&gt;${sender} has sent you a message.&lt;/p&gt;`;
                console.log(message); // &lt;p&gt;& lt;script& gt;alert("abc")& lt;/script& gt; has sent you a message.&lt;/p&gt;

                //--------------------------------------------------------------------------

                // 应用2：多语言转换（国际化处理）
                i18n`Welcome to ${siteName}, you are visitor number ${visitorNumber}!` // "欢迎访问xxx, 您是第xxx位访问者！"

                //--------------------------------------------------------------------------

                // 应用3：对其他语言/结构进行转换
                // 下面的代码通过jsx函数，将DOM字符串转换为React对象
                jsx`
                    &lt;div&gt;
                    &lt;input
                        ref='input'
                        onchange='${this.handleChange}'
                        defaultValue = '${this.state.value}' /&gt;
                        ${this.state.value}
                    &lt;/div&gt;
                `
            </code>
        </pre>
        <script src="scripts/libs/highlight.pack.js"></script>
        <script src="scripts/15.js"></script>
        <script>
            hljs.initHighlightingOnLoad();
        </script>
    </body>
</html>